
package bible.sunflower.util;

import java.awt.image.BufferedImage;
import java.io.File;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;

import org.apache.log4j.Logger;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.Binarizer;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.EncodeHintType;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.Result;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;

/**
 * 二维码
 * @author zhangyp
 *
 */
public class Dimension2CodeUtil {
	
	static Logger log = Logger.getLogger( Dimension2CodeUtil.class );
	
	/**
	 * 将内容编码成二维码图片
	 * @param content
	 * @return
	 */
	public static void encode(String content, String filepath, String fileFormat, int width, int height  ){
       try{		     
	      MultiFormatWriter multiFormatWriter = new MultiFormatWriter();		     
	      Map hints = new HashMap();
	      hints.put(EncodeHintType.CHARACTER_SET, "GBK");
	      BitMatrix bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, width, height,hints);		     
	      File file = new File( filepath );
	      MatrixToImageWriter.writeToFile(bitMatrix, fileFormat, file);
	   }catch (Exception e) {
	      e.printStackTrace();
	      log.error("2code error...", e);
	   }
	}
	
	/**
	 * 根据图片路径将图片解码，返回内容
	 * @param filepath
	 * @return
	 */
	public static String decode(String filepath){
		String content = "";
		try{
            MultiFormatReader formatReader = new MultiFormatReader();
			File file = new File(filepath);
			BufferedImage image = ImageIO.read(file);
			LuminanceSource source = new BufferedImageLuminanceSource(image);
			Binarizer  binarizer = new HybridBinarizer(source);
			BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);
			Map hints = new HashMap();
			hints.put(EncodeHintType.CHARACTER_SET, "GBK");
			Result result = formatReader.decode(binaryBitmap,hints);
			//输出编码信息
			log.debug("2code result = "+ result.toString());
			//输出二维码的编码格式
			log.debug("2code resultFormat = "+ result.getBarcodeFormat());
			//输出二维码的编码字符串
			log.debug("2code resultText = "+ result.getText());			   
            content = result.getText();
		} catch (Exception e) {
			e.printStackTrace();
			log.error("2code decode error...", e);
		}
		return content;
	}

}
